//
//  LaunchScreenManager.swift
//  SwiftProject
//
//  Created by qindong on 2021/3/8.
//

// MARK:- 启动页管理器 用于加载网络广告图

import UIKit

let showTime : Int = 3

class LaunchScreenManager: NSObject {
    
    let launchScreenView : LaunchScreenView?
    
    var dict : Dictionary<String, Any>?
    
    var count : Int = 0
    
    lazy var countTime : Timer = {
        return Timer.scheduledTimer(timeInterval: 1.0, target: self, selector: #selector(countDown), userInfo: nil, repeats: true)
    }()
    
    static let shared : LaunchScreenManager = LaunchScreenManager()
    
    override init() {
        launchScreenView = LaunchScreenView(filePathString: "")
    }
    
    func showLaunchAnimationView() {
        if #available(iOS 13.0, *) {
//            if UIApplication.shared.connectedScenes.count > 0 {
//                for scene in UIApplication.shared.connectedScenes {
//                    ((scene as? UIWindowScene)!.delegate as! UIWindowSceneDelegate).window!!.addSubview(launchScreenView!)
//                    break
//                }
//            } else {
                UIApplication.shared.windows.first?.addSubview(launchScreenView!)
//            }
        } else {
            AppDelegate.appDelegate.window?.addSubview(launchScreenView!)
            // Fallback on earlier versions
        }
        showAdView()
    }
    
    func showAdView() {
        dict = UserDefaults.standard.value(forKey: "adImageName") as? Dictionary<String, Any>
        if dict != nil {
            let filePath : String! = getFilePathWithImageName(imageName: "launchImage\(dict!["id"]!).png")
            let isExist : Bool = isFileExistWithFilePath(filePath: filePath)
            if isExist {
                launchScreenView?.launchView?.removeFromSuperview()
                launchScreenView?.filePath = filePath
                launchScreenView?.showAdViewWith(time: showTime)
                launchScreenView?.pushBlock = {
                    // 点击广告跳转
                    
                }
                launchScreenView?.dismissBlock = {
                    // 点击跳过
                    self.launchAnimationViewDismiss()
                }
            }
            startTimer()
        }
        // 不管有没有缓存 都重新请求有没有新图
//        getAdImage()
    }
    
    // 网络请求广告图
    func getAdImage() {

    }
    
    func downloadAdImageWith(dict : Dictionary<String, Any>) {
        if dict["img"] == nil {
            return
        }
        // 广告图地址
//        let url : String = dict["img"] as! String + "?imageView2/1/w/" + String(format: "%.0f", Float(SCREEN_WIDTH) * Float(UIScreen.main.scale)) + "/h/" + String(format: "%.0f", Float(SCREEN_HEIGHT) * Float(UIScreen.main.scale))
        // 保存地址


    }
    
    func deleteOldImage() {
        let dict : Dictionary<String, Any>? = (UserDefaults.standard.value(forKey: "adImageName") as? Dictionary<String, Any>)
        if dict != nil {
            let newId : Int? = Int(self.dict!["id"] as! String)
            let oldId : Int? = Int(dict!["id"] as! String)
            if (oldId != newId) {
                let filePath : String! = self.getFilePathWithImageName(imageName: "launchImage" + String(oldId!) + ".png")
                do {
                    try FileManager.default.removeItem(atPath: filePath)
                } catch {
                    
                }
            }
        }
    }
    
    // 开启定时
    func startTimer() {
        count = showTime
        RunLoop.main.add(countTime, forMode: .common)
    }
    
    @objc func countDown() {
        count -= 1
        if launchScreenView?.countBtn != nil {
            launchScreenView?.countBtn!.setTitle("跳过 " + String(count), for: .normal)
        }
        if count == 0 {
            launchAnimationViewDismiss()
        }
    }
    
    // 广告页消失
    func launchAnimationViewDismiss() {
        launchAnimationViewDismiss(delay: 0)
        countTime.invalidate()
        countTime = Timer()
    }
    
    // 广告页延迟消失
    func launchAnimationViewDismiss(delay : Float) {
        UIView.animate(withDuration: 1, delay: TimeInterval(delay), options: [.beginFromCurrentState,.curveLinear]) {
            self.launchScreenView?.alpha = 0
        } completion: { (finished) in
            self.launchScreenView?.removeFromSuperview()
        }
    }
    
    func pushToAd() {
        if dict!["url"] as! String == "" {
            return
        }
        launchScreenView?.removeFromSuperview()
        
        
    }
    
    func isFileExistWithFilePath(filePath : String) -> Bool {
        let fileManager : FileManager = FileManager.default
        var isDirectory = ObjCBool.init(false)
        return fileManager.fileExists(atPath: filePath, isDirectory: &isDirectory)
    }
    
    func getFilePathWithImageName(imageName : String?) -> String? {
        if imageName != nil {
            let paths : Array<String> = NSSearchPathForDirectoriesInDomains(.cachesDirectory, .userDomainMask, true)
            return paths.first! + "/" + imageName!
        }
        return nil
    }
    
    deinit {
        countTime.invalidate()
        countTime = Timer()
    }
}
